package com.loong.musicdemo.ui.video.activity;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.loong.musicdemo.R;
import com.loong.musicdemo.adapter.HotSearchAdapter;
import com.loong.musicdemo.adapter.NormalMVAdapter;
import com.loong.musicdemo.adapter.SearchHistoryAdapter;
import com.loong.musicdemo.adapter.SuggestionAdapter;
import com.loong.musicdemo.model.MV;
import com.loong.musicdemo.model.SearchInfo;
import com.loong.musicdemo.util.dataDeal.SearchDeal;
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.ArrayList;
import java.util.List;

public class SearchMvActivity extends AppCompatActivity {

    //全局数据
    private static final int HOT_SEARCH_HANDLER = 1;//接收热搜适配器标志
    private static final int HISTORY_SEARCH_HANDLER = 2;//接收历史记录适配器标志
    private static final int SUGGESTION_SEARCH_HANDLER = 3;//接收建议列表适配器标志
    private static String keywords;//搜索关键字

    private Toolbar toolbar;
    private MaterialSearchView searchView;
    private SharedPreferences historyPreference;
    private RecyclerView record_view, hot_search_view, search_suggest_list, recyclerViewResult;//结果列表
    private RelativeLayout history_content;
    private ImageView clear_history;
    private LinearLayout search_main_content;

    //对应三个地方的适配器
    private static SearchHistoryAdapter historyAdapter;//历史记录适配器
    private static SuggestionAdapter suggestionAdapter;//建议适配器
    private static HotSearchAdapter hotAdapter;//热搜适配器
    private static NormalMVAdapter resultAdapter;//查找数据适配器

    //对应三个地方数据显示
    private static List<String> historyRecord = new ArrayList<>();//历史记录
    private static List<String> searchSuggestions = new ArrayList<>();//搜索建议
    private static List<SearchInfo> searchInfoList = new ArrayList<>();//搜索信息
    private static List<MV> resultMV = new ArrayList<>();//搜索到的MV结果

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        setContentView(R.layout.activity_search_mv);
        initView();//初始化布局
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("MV搜索");
            actionBar.setDisplayHomeAsUpEnabled(true);//若工具栏可用,则显示Home菜单
        }
        initHistoryRecord();//初始化历史记录
        initRecordView();//初始化历史页列表
        initHotSearchView();//初始化热搜列表
        initSearchSuggestionView();//初始化建议列表
        initResultView();//初始化结果视图
        new SearchTask().execute();//初始化热搜数据
    }

    /*
       初始化所有的控件
    */
    private void initView() {
        searchView = findViewById(R.id.search_view);
        toolbar = findViewById(R.id.toolbar);
        historyPreference = getSharedPreferences("mv_search_history", MODE_PRIVATE);
        record_view = findViewById(R.id.record_view);
        history_content = findViewById(R.id.history_content);
        hot_search_view = findViewById(R.id.hot_search_view);
        clear_history = findViewById(R.id.clear_history);
        search_suggest_list = findViewById(R.id.search_suggest_list);
        search_main_content = findViewById(R.id.search_main_content);
        recyclerViewResult = findViewById(R.id.mv_result);//MV查找结果
        historyAdapter = new SearchHistoryAdapter(historyRecord, handler);//传入handler,接收适配器数据
        suggestionAdapter = new SuggestionAdapter(searchSuggestions, handler);
        hotAdapter = new HotSearchAdapter(searchInfoList, handler);//传入handler,接收适配器数据
    }

    /**
     * handler用于提供热搜列表点击数据同步
     */

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            keywords = msg.obj.toString();
            switch (msg.what) {
                case HISTORY_SEARCH_HANDLER:
                    //历史记录适配器数据
                    searchMV();//搜索MV数据
                    break;
                case HOT_SEARCH_HANDLER:
                case SUGGESTION_SEARCH_HANDLER:
                    if (!historyRecord.contains(keywords)) {
                        addToHistoryRecord(keywords);
                        history_content.setVisibility(View.VISIBLE);//显示历史记录
                    }
                    searchMV();//搜索MV数据
                default:
                    break;
            }
        }
    };

    /**
     * MV 搜索
     */
    private void searchMV() {
        new SearchResultTask().execute();
        resultStatusView();
    }

    //搜索状态显示
    private void searchStatusView() {

        //搜索栏不显示
        search_main_content.setVisibility(View.VISIBLE);

        //结果不显示
        recyclerViewResult.setVisibility(View.GONE);
    }

    /**
     * 显示结果状态
     */
    private void resultStatusView() {
        //搜索栏不显示
        search_main_content.setVisibility(View.GONE);
        //结果显示
        recyclerViewResult.setVisibility(View.VISIBLE);
        //建议列表不显示
        search_suggest_list.setVisibility(View.GONE);
    }

    //初始化历史记录
    private void initHistoryRecord() {
        int historySize = historyPreference.getInt("historySize", 0);
        if (historySize != 0) {
            for (int i = 0; i < historySize; i++) {
                String item = historyPreference.getString("history_" + i, null);
                historyRecord.add(item);
            }
        }
    }

    //初始化历史记录RecyclerView
    private void initRecordView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        record_view.setLayoutManager(layoutManager);
        record_view.setAdapter(historyAdapter);
        if (historyRecord.size() != 0) {
            history_content.setVisibility(View.VISIBLE);
        } else {
            history_content.setVisibility(View.GONE);
        }
        initClearHistoryHandler();
    }

    //初始化热搜视图
    private void initHotSearchView() {
        hot_search_view.setAdapter(hotAdapter);
    }

    //初始化搜索建议recyclerview
    private void initSearchSuggestionView() {
        LinearLayoutManager manager = new LinearLayoutManager(getApplicationContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        search_suggest_list.setLayoutManager(manager);
        search_suggest_list.setAdapter(suggestionAdapter);
        if (searchSuggestions.size() == 0) {
            search_suggest_list.setVisibility(View.GONE);
            search_main_content.setVisibility(View.VISIBLE);
            search_suggest_list.setVisibility(View.VISIBLE);
            search_main_content.setVisibility(View.GONE);
        }
    }

    //初始化结果视图
    private void initResultView() {
        resultAdapter = new NormalMVAdapter(resultMV);
        recyclerViewResult.setAdapter(resultAdapter);
        recyclerViewResult.setVisibility(View.GONE);//一开始不显示
    }

    //清空历史的点击事件
    private void initClearHistoryHandler() {
        clear_history.setOnClickListener(v -> new QMUIDialog.MessageDialogBuilder(SearchMvActivity.this)
                .setTitle("客官")
                .setMessage("确定要删除吗？")
                .addAction("取消", (dialog, index) -> dialog.dismiss())
                .addAction(0, "删除", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
                    SharedPreferences.Editor editor = historyPreference.edit();
                    editor.clear();
                    editor.apply();
                    historyRecord.clear();
                    historyAdapter.notifyDataSetChanged();
                    history_content.setVisibility(View.GONE);
                    dialog.dismiss();
                }).show());
    }

    /**
     * 初始菜单
     *
     * @param menu 菜单
     * @return 设置成功与否
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search_view, menu);
        MenuItem item = menu.findItem(R.id.action_search);
        searchView.setMenuItem(item);
        initSearchViewHandler();
        return super.onCreateOptionsMenu(menu);
    }

    //将搜索记录加入到历史记录
    private void addToHistoryRecord(String query) {
        historyRecord.add(query);
        SharedPreferences.Editor editor = historyPreference.edit();
        //存取长度
        editor.putInt("historySize", historyRecord.size());
        //每次只存取最后一个
        editor.putString("history_" + (historyRecord.size() - 1), query);
        editor.apply();
        historyAdapter.notifyDataSetChanged();
    }

    //添加searchView的事件监听器
    private void initSearchViewHandler() {
        searchView.setVoiceSearch(true);//显示
        searchView.showSearch();
        searchView.setCursorDrawable(R.drawable.color_cursor_white);//背景颜色
        searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {//文本提交
                if (!historyRecord.contains(query)) {
                    addToHistoryRecord(query);//添加历史记录
                }
                keywords = query;//关键词
                searchMV();//搜索
                history_content.setVisibility(View.VISIBLE);//显示历史记录
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {//文本改变时
                if (!TextUtils.isEmpty(newText)) {
                    search_suggest_list.setVisibility(View.VISIBLE);
                    search_main_content.setVisibility(View.GONE);
                    searchStatusView();
                    new SuggestionTask(newText).execute();//获取搜索关键词对应信息
                } else {//关键词为空时
                    search_suggest_list.setVisibility(View.GONE);
                    search_main_content.setVisibility(View.VISIBLE);
                    searchStatusView();
                }
                return false;
            }
        });

        searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
            @Override
            public void onSearchViewShown() {
                search_main_content.setVisibility(View.VISIBLE);
                searchStatusView();
            }

            @Override
            public void onSearchViewClosed() {
                if (resultMV.size() > 0) {
                    resultStatusView();
                } else {
                    searchStatusView();
                }
            }
        });
    }

    /**
     * 动态显示搜索建议
     */
    static class SuggestionTask extends AsyncTask<String, Void, List<String>> {
        private String keyword;

        public SuggestionTask(String keyword) {
            this.keyword = keyword;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(List<String> strings) {
            super.onPostExecute(strings);
            searchSuggestions.clear();
            if (strings != null) {
                searchSuggestions.addAll(strings);
            }
            suggestionAdapter.notifyDataSetChanged();
        }

        @Override
        protected List<String> doInBackground(String... strings) {
            return SearchDeal.getSearchSuggestions(keyword);
        }
    }

    /**
     * 搜索结果
     */
    static class SearchResultTask extends AsyncTask<Void, Void, List<MV>> {

        @Override
        protected List<MV> doInBackground(Void... voids) {
            //搜索请求
            return SearchDeal.getSearchMV(keywords);
        }

        @Override
        protected void onPostExecute(List<MV> mvs) {
            super.onPostExecute(mvs);
            //先清空原有数据
            resultMV.clear();
            resultMV.addAll(mvs);
            resultAdapter.notifyDataSetChanged();//更改数据
        }
    }

    /**
     * 退出当前活动
     *
     * @param item 菜单项
     * @return 结果
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;//返回前一个活动
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 热搜数据
     */
    static class SearchTask extends AsyncTask<SearchInfo, Void, List<SearchInfo>> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(List<SearchInfo> searchInfo) {
            super.onPostExecute(searchInfo);
            if (searchInfo != null) {//不为空则
                searchInfoList.addAll(searchInfo);
                hotAdapter.notifyDataSetChanged();
            }
        }

        @Override
        protected List<SearchInfo> doInBackground(SearchInfo... searchInfo) {
            return SearchDeal.getSearchHotDetail();
        }
    }

    /**
     * 搜索框返回建
     */
    @Override
    public void onBackPressed() {
        if (searchView.isSearchOpen()) {
            searchView.closeSearch();
        } else {
            super.onBackPressed();
        }
    }
}
